/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import ejb.SponsorUserManager;
import ejb.SponsoredEvent;
import ejb.SponsoredEventManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Stefano
 */
@WebServlet(name = "IMDSponsoredEventServlet", urlPatterns = {"/IMDSponsoredEventServlet"})
public class IMDSponsoredEventServlet extends HttpServlet {

    @EJB
    private SponsorUserManager sponsorUserManager;
    @EJB
    private SponsoredEventManager sponsoredEventManager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();



        try {
            String eid, tags, action, name;
            int maximpression;

            Date start_date = null, end_date = null;
            String sd, ed, accessToken, userId;
            HttpSession session = request.getSession();
            userId = session.getAttribute("userid").toString();
            accessToken = session.getAttribute("token").toString();
            
            
            action = request.getParameter("action");
            eid = request.getParameter("eid");

            if (action.equals("insert")) {

                name = request.getParameter(eid);
                

                tags = request.getParameter("tags-form");
                maximpression = Integer.parseInt(request.getParameter("max-imp"));


                DateFormat df = new SimpleDateFormat("dd/MM/yy");
                df.setLenient(false);


                start_date = df.parse(sd = request.getParameter("data-from"));
                end_date = df.parse(ed = request.getParameter("data-to"));

                if (sponsorUserManager.isNewSponsorUser(userId)) {
                    sponsorUserManager.addSponsorUser(userId, 0);
                    out.println("DEBUG: utente inserito in SponsorUser");
                    out.println("<br>");
                }

                if (sponsorUserManager.findSponsorUser(userId).getCredit() >= maximpression) {
                    sponsorUserManager.payCredit(userId, maximpression);
                    sponsoredEventManager.addSponsoredEvent(userId, eid, start_date, end_date, maximpression, name, tags);
                    out.println("<h3>Questo è l'evento che hai appena sponsorizzato:</h3> ");
                    out.println("<hr>");
                    out.println("</br>");
                    out.println("Nome: " + name + "</br>");
                    out.println("uid: " + userId + "</br>");
                    out.println("eid: " + eid + "</br>");
                    out.println("DA: " + sd + "</br>");
                    out.println("A: " + ed + "</br>");
                    out.println("max impression: " + maximpression + "</br>");
                    out.println("tags: " + tags + "</br>");
                    out.println("<hr>");
                } else {
                    out.println("<h3>Non hai abbastanza soldi!</h3> ");
                    out.println("<hr>");
                    int r = maximpression - sponsorUserManager.findSponsorUser(userId).getCredit();
                    out.println("Ti servono: " + r + " crediti");
                    out.println("<br>");

                    out.println("<a href=\"/delo-war/events/credit_recharge.jsp\">Ricarica Credito</a>");
                    out.println("<br>");
                    out.println("<hr>");

                }
            } else if (action.equals("delete")) {
               // int remain = sponsoredEventManager.findSposoredEventEid(eid).getMaxImpression() - sponsoredEventManager.findSposoredEventEid(eid).getImpression();
                //sponsorUserManager.rechargeCredit(userId, remain);             
                out.println("<title>Sponsorizzazione eliminata</title>");  
                out.println("<h3>Questo è l'evento sponsorizzato che hai appena Eliminato:</h3> ");


                out.println("Nome: " + sponsoredEventManager.findSposoredEventEid(eid).getName() + "</br>");
                out.println("eid: " + eid + "</br>");
                sponsoredEventManager.deleteSposnoredEventEid(eid);


               // out.println("Verrai reindirizzato alla gestione sponsorizzazioni!");
                //out.println("Se il redirect non dovesse funzionare, click <a href=\"/delo-war/SponsoredEventManagerServlet\">qui</a>.");

                

            } else if (action.equals("modify")) {
                SponsoredEvent sevent = new SponsoredEvent();
                
                sevent = sponsoredEventManager.findSposoredEventEid(eid);
                request.setAttribute("sevent", sevent);
                ServletContext sc = getServletContext();
                RequestDispatcher rd = sc.getRequestDispatcher("/ModifySponsoredEvent.jsp");
                rd.forward(request, response);
                
            } else if (action.equals("modifyInsert")) {
                SponsoredEvent sponse = new SponsoredEvent();
                name = request.getParameter("name");
                


                tags = request.getParameter("tags-form");
                maximpression = Integer.parseInt(request.getParameter("max-imp"));
                DateFormat df = new SimpleDateFormat("dd/MM/yy");
                df.setLenient(false);


                start_date = df.parse(sd = request.getParameter("data-from"));
                end_date = df.parse(ed = request.getParameter("data-to"));

                sponse = sponsoredEventManager.findSposoredEventEid(eid);
                sponse.setTag(tags);
                sponse.setMaxImpression(maximpression);
                sponse.setStartDate(start_date);
                sponse.setEndDate(end_date);

                out.println("<br />");
               
                sponsoredEventManager.editSponsoredEvent(sponse);
                out.println("<b>Evento modificato con successo</b>");
                



            } else if (action.equals("recharge")) {
                int money, lastCredit, newCredit;
                out.println("<h3>Dettagli della ricarica:</h3>");
                out.println("<hr>");
                out.println("<br>");
                if (sponsorUserManager.isNewSponsorUser(userId)) {
                    sponsorUserManager.addSponsorUser(userId, 0);
                    out.println("DEBUG: utente inserito in SponsorUser");
                    out.println("<br>");
                }

                lastCredit = sponsorUserManager.findSponsorUser(userId).getCredit();
                out.println("Credito PRIMA della ricarica: " + lastCredit + " impressions");
                out.println("<br>");

                money = Integer.parseInt(request.getParameter("money"));
                out.println("Importo della ricarica: " + money + " impressions");
                out.println("<br>");

                sponsorUserManager.rechargeCredit(userId, money);
                newCredit = sponsorUserManager.findSponsorUser(userId).getCredit();
                out.println("Credito DOPO della ricarica: " + newCredit + " impressions");
                out.println("<br>");




                out.println("<hr>");
            } else {
                out.println("ERRORE NON DOVREI MAI ENTRARE QUI");
            }

          

        } catch (Exception e) {
        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
